#include "GoalKeeper.h"
#include "GKStates.h"
#include "Params.h"
#include "Team.h"
#include "Utils.h"

#include <vector>

GoalKeeper::GoalKeeper(GameState* game, Team* team, int homeRegionId, sf::Color drawColor)
: BasePlayer(game, team, homeRegionId, drawColor, Params::GKMaxSpeed)
{

	m_FSM = new StateMachine<GoalKeeper>(this);
	m_FSM->SetGlobalState(GKGlobalState::Istance());
	m_FSM->SetCurrentState(GKIdle::Istance());
	m_FSM->SetPreviousState(NULL);
}

GoalKeeper::~GoalKeeper()
{
	delete m_FSM;
}

void GoalKeeper::SetUserControl(bool controlled)
{
	if(controlled)	m_FSM->ChangeState(GKUserControlled::Istance());
	else			m_FSM->ChangeState(GKIdle::Istance());
}

void GoalKeeper::ToHome()
{
	if (!m_FSM->IsInState((*GKHoldBall::Istance())) && !m_FSM->IsInState((*GKUserControlled::Istance())))
	{
		m_FSM->ChangeState(GKIdle::Istance());
	}
}

BasePlayer* const GoalKeeper::FindPass()
{
	BasePlayer* passTo = NULL;
	float bestPass = 0.f;

	std::vector<BasePlayer*> mates = m_team->Players();

	for ( std::vector<BasePlayer*>::iterator it = mates.begin(); it != mates.end(); ++it)
	{
		if ((*it) !=  this)
		{
			float currentPassValue = CanPass((*it));
			if (bestPass < currentPassValue)
			{
				bestPass = currentPassValue;
				passTo = (*it);
			}
			(*it)->pVal.SetString(NumberToString(currentPassValue));//FIXME REMOVE
		}
	}


	return passTo;
}

void GoalKeeper::CalculateInterposeWeight()
{
	if(!m_team->InControl()){
		if (m_team->DistBallToHomeGoal()<=150.f)Steering()->SetInterposeWeight( 1.f - (m_team->DistBallToHomeGoal() * 0.001f ) );
		else Steering()->SetInterposeWeight( 0.3f );
	}
	else Steering()->SetInterposeWeight(0.3f);
}


void GoalKeeper::Update(const sf::Input& input)
{
	//if(!IsUserControlled()) 
		m_FSM->Update();
	BasePlayer::Update(input);
}

void GoalKeeper::OnDraw(sf::RenderWindow & render)
{
	BasePlayer::OnDraw(render);
}
